export class WebMessage {
  // 构造需传入websocket连接地址
  constructor() {
    this.wsUrl = undefined
    this.state = -1
    this.eventPool = [] //事件池
  }

  // 初始化时连接websocket
  init(userId) {
    const host = location.host
    const port = location.port
    const protocol = location.protocol
    let wsUrl = ''
    if (protocol === 'http:') {
      wsUrl += 'ws://'
    } else if (protocol === 'http:') {
      wsUrl += 'wss://'
    } else {
      console.error('无法解析的protocol:' + protocol)
      return
    }
    wsUrl += host
    if (port) {
      wsUrl += ':' + port
    }
    wsUrl += process.env.VUE_APP_BASE_API + '/websocket?userId=' + userId
    this.ws = null
    this.wsUrl = wsUrl
    this.connectWs(this.wsUrl)
  }

  // 连接websocket
  connectWs(wsUrl) {
    this.ws = new WebSocket(wsUrl)
    this.ws.onopen = () => {
      this.state = 0
      console.log('ws连接成功！')
    }
    this.ws.onclose = () => {
      this.state = -1
      this.ws = null
      console.log('ws断开连接，正在重连...')
      setTimeout(() => {
        this.connectWs(wsUrl)
      }, 500)
    }
    this.ws.onmessage = e => {
      let msg = {}
      try {
        msg = JSON.parse(e.data)
      } catch (ex) {
        console.error(`websocket消息 ${e.data} 不是有效的JSON格式`)
      }
      const moduleName = msg.moduleName
      const _event = this.eventPool.find(ep => ep.name === moduleName)
      if (_event) {
        _event.fns.forEach(fn => {
          fn(msg.msgBody)
        })
      }
    }
  }
  createEvent(name, fn) {
    //注册onmessage事件，防止覆盖原有事件
    const existEvent = this.eventPool.find(e => e.name === name)
    if (existEvent) {
      existEvent.fns.push(fn)
      console.log('已存在websocket模块：' + name)
    } else {
      console.log('注册websocket事件，模块名：' + name)
      this.eventPool.push({
        name,
        fns: [fn]
      })
    }
  }
}
